import React from 'react'
import { Layout, Menu, Collapse, Switch } from 'antd'
import PropTypes from 'prop-types'
import Trigger from './Trigger'
import 'css/index/weather/weather.scss'
import SevenDays from './SevenDays'
import Scrollbar from 'react-smooth-scrollbar'
import { connect } from 'react-redux'
import Gdu from './dayEcharts/Gdu'
import Temperature from './dayEcharts/Temperature'
import FarmlandWeather from './famlandWeather/FarmlandWeather'
import moment from 'moment'
import zh from 'moment/locale/zh-cn'
moment.locale('zh')
import Information from './Sider/Information'
import { showList } from '_redux/actions/weather'
import Insights from './Sider/Insights'
import Decisions from './Sider/Decisions'
import Coefficient from './Coefficient'
import GduSummary from './Summary/Gdu'
import RainfallSummary from './Summary/Rainfall'
import ExtremeTempMonth from './Summary/ExtremeTempMonth'
import ExtremeTempYear from './Summary/ExtremeTempYear'

import minus from 'images/index/weather/minus.png'
import plus from 'images/index/weather/plus.png'
import DatePicker from './DatePicker'

const { Sider } = Layout
const SubMenu = Menu.SubMenu
const Panel = Collapse.Panel

class Weather extends React.Component {
  state = {
    leftCollapsed: false,
    rightCollapsed: false,
    summary: [],
    unit: true,
    echartsArr: [],
    start: 90,
    end: 100,
    startDate: moment().subtract(182, 'days'),
    endDate: moment(),
  };
  componentDidMount() {
    const { show } = this.props.weather
    if (show) {
      this.weather.scrollIntoView(true)
    }
  }
  componentDidUpdate(prevProps) {
    const { show } = this.props.weather
    if (show && !prevProps.weather.show) {
      this.weather.scrollIntoView(true)
    }
  }
  onLeftCollapse = (collapsed) => {
    this.setState({ leftCollapsed: !collapsed })
  }
  onRightCollapse = (collapsed) => {
    this.setState({ rightCollapsed: collapsed })
  }
  menuClick = ({ key, keyPath }) => {
    const { scrollbar } = this.$container
    const {summary} = this.state
    if (keyPath[1] === 'history') {
      for (let sum of summary) {
        if (sum.key === key) {
          scrollbar.scrollIntoView(document.querySelector(`#${key}`))
          return
        }
      }
    } else {
      scrollbar.scrollIntoView(document.querySelector(`#${key}`))
    }
  }
  filter = (key) => {
    switch (key) {
    case 'gduSummary':
      return GduSummary
    case 'rainfall':
      return RainfallSummary
    case 'extreme_temperature_year':
      return ExtremeTempYear
    case 'extreme_temperature_month':
      return ExtremeTempMonth
    default:
      break
    }
  }
  action = (key) => {
    const { summary } = this.state
    const target = [...summary]
    for (let sum of summary) {
      if (sum.key === key) {
        // 移除
        this.setState({
          summary: target.filter(sum => sum.key !== key)
        })
        return
      }
    }
    target.push({
      key,
      dom: this.filter(key),
    })
    this.setState({
      summary: target
    })
  }
  unitChange = (checked) => {
    this.setState({
      unit: checked
    })
  }
  callback = (echart) => {
    const echartsArr = [
      ...this.state.echartsArr,
      echart
    ]
    if (echartsArr.length === 3) {
      echarts.connect(echartsArr)
      const myChart = echartsArr[2]
      myChart.on('datazoom', ({start, end}) => {        
        this.setState({
          start,
          end,
        })

      })
    } else if (echartsArr.length > 3) { 
      return
    }
    this.setState({
      echartsArr
    })
  }
  close = (e) => {
    e.preventDefault()
    this.props.showList(false)
  }
  getDate =(startDate, endDate) =>{
    this.setState({
      startDate,
      endDate
    })
  }
  render() {
    console.log('weather render')
    const { show } = this.props.weather
    const { feature } = this.props.feature
    const landId = feature.getId().replace('tb_farmland.', '')
    const { unit, startDate, endDate, leftCollapsed, rightCollapsed, endOpen, start, end, dateChangeEnd } = this.state
    const props = {
      landId,
      leftCollapsed,
      rightCollapsed,
      startDate,
      endDate,
      unit,
      start,
      end,
      dateChangeEnd,
    }
    
    return (
      show ? <div className='weather-layout' ref={weather => this.weather = weather}>
        <div className='title'>
          <h3>{this.props.feature.feature.get('name')}-{'天气'}</h3>
          <a href="#" className='closer' onClick={this.close}></a>
        </div>
        <Layout className='weather'>
          <Sider
            collapsible
            className='left'
            collapsed={this.state.leftCollapsed}
            trigger={null}
            width={150}
            collapsedWidth={0}
          >
            <Menu defaultOpenKeys={['everyDay']}
              onClick={this.menuClick}
              mode="inline">
              <SubMenu
                key="everyDay"
                title={<span>每日</span>}
              >
                <Menu.Item key="temperature">
                  <span className='icon-uniE900'>温度</span>
                </Menu.Item>
                <Menu.Item key="gdu">
                  <span className='icon-uniE900'>GDU累计</span>
                </Menu.Item>
                {/* <Menu.Item key="pcpn">
                <span className='icon-uniE900'>降雨量（气象站）</span>
              </Menu.Item> */}
                <Menu.Item key="farmlandWeather">
                  <span className='icon-uniE900'>降雨+灌溉</span>
                </Menu.Item>
              </SubMenu>
              <SubMenu
                key="history"
                title={<span>历史汇总</span>}
              >
                <Menu.Item key="rainfall">
                  <span className='icon-uniE900'>月平均降水</span>
                  <div className='action' onClick={this.action.bind(this, 'rainfall')}>
                    <img src={this.state.summary.filter(summary => summary.key === 'rainfall').length === 0 ? plus : minus} alt="" />
                  </div>
                </Menu.Item>
                <Menu.Item key="gduSummary">
                  <span className='icon-uniE900'>历年GDU</span>
                  <div className='action' onClick={this.action.bind(this, 'gduSummary')}>
                    <img src={this.state.summary.filter(summary => summary.key === 'gduSummary').length === 0 ? plus : minus} alt="" />
                  </div>
                </Menu.Item>
                <Menu.Item key="extreme_temperature_year">
                  <span className='icon-uniE900'>极端温度（年）</span>
                  <div className='action' onClick={this.action.bind(this, 'extreme_temperature_year')}>
                    <img src={this.state.summary.filter(summary => summary.key === 'extreme_temperature_year').length === 0 ? plus : minus} alt="" />
                  </div>
                </Menu.Item>
                <Menu.Item key="extreme_temperature_month">
                  <span className='icon-uniE900'>极端温度（月）</span>
                  <div className='action' onClick={this.action.bind(this, 'extreme_temperature_month')}>
                    <img src={this.state.summary.filter(summary => summary.key === 'extreme_temperature_month').length === 0 ? plus : minus} alt="" />
                  </div>
                </Menu.Item>
              </SubMenu>
              <Coefficient landId={landId} />
            </Menu>
          </Sider>
          <Layout>
            <Trigger
              onClick={this.onLeftCollapse}
              collapsed={!this.state.leftCollapsed} />
            <Scrollbar ref={c => this.$container = c}>
              <div className='layout-content' ref={content => this.content = content}>
                <SevenDays feature={this.props.feature} />
                <div className='datepicker'>
                  <DatePicker getDate={this.getDate}/>
                  <Switch checkedChildren="°C" unCheckedChildren="°F" defaultChecked onChange={this.unitChange} />
                </div>
                <Temperature callback={this.callback} type={'temperature'} {...props} />
                <Gdu callback={this.callback} type={'gdu'} {...props} />
                <FarmlandWeather callback={this.callback} type={'farmlandWeather'} {...props} />
                {
                  this.state.summary.map(summary => {
                    const Dom = summary.dom
                    return <Dom key={summary.key} $container={this.$container} type={summary.key} {...props} />
                  })
                }
              </div>
            </Scrollbar>
            <Trigger
              onClick={this.onRightCollapse}
              collapsed={this.state.rightCollapsed} />
          </Layout>
          <Sider
            collapsible
            className='right'
            collapsed={this.state.rightCollapsed}
            onCollapse={this.onRightCollapse}
            trigger={null}
            width={250}
            collapsedWidth={0}
          >
            <Collapse defaultActiveKey={['information']} accordion>
              <Panel header="信息" key="information">
                <Information landId={landId} />
              </Panel>
              <Panel header="见解" key="2">
                <Insights landId={landId} />
              </Panel>
              <Panel header="决策" key="3">
                <Decisions landId={landId} />
              </Panel>
            </Collapse>
          </Sider>
        </Layout>
      </div> : null
    )
  }
}
Weather.propTypes = {
  feature: PropTypes.object,
  weather: PropTypes.object,
  showList: PropTypes.func,
}
export default connect(({ feature, weather }) => ({ 
  feature,
  weather,
}), (dispatch) => ({
  showList: function(flag) {
    dispatch(showList(flag))
  }
}))(Weather)